package pers.vic.upload.login.service;

import cn.xuqiudong.common.base.model.BaseResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import pers.vic.upload.config.redis.RedisService;
import pers.vic.upload.constant.ResultEnum;
import pers.vic.upload.constant.SessionAttr;
import pers.vic.upload.login.dao.LoginDao;
import pers.vic.upload.login.model.AfterLogin;
import pers.vic.upload.login.model.User;
import pers.vic.upload.utils.SessionHelper;
import pers.vic.upload.utils.UploadCommonUtils;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * 描述:
 * @author Vic.xu
 * @date 2022-07-06 11:29
 */
@Service
public class LoginService {

    /**
     *  用户过期时间:4个小时
     */
    public static final long TIME = 4 * 60 * 60;

    @Resource
    private LoginDao loginDao;

    @Resource
    private RedisService redisService;

    public BaseResponse<?> login(String username, String password, HttpServletRequest request) {
        User user = loginDao.findUser(username);
        if (user == null) {
            return BaseResponse.error(ResultEnum.INVALID_USER);
        }
        if (!user.isEnabled()) {
            return BaseResponse.error(ResultEnum.DISABLE_USER);
        }
        if (!StringUtils.equals(user.getPassword(), UploadCommonUtils.encrypt(username, password))) {
            return BaseResponse.error(ResultEnum.INVALID_USER);
        }
        request.getSession(true).setAttribute(SessionAttr.SESSION_USER, user);
        SessionHelper.storageSessionUser(request, user);
        String id = request.getSession().getId();

        AfterLogin afterLogin = new AfterLogin();
        afterLogin.setUser(user);
        afterLogin.setSessionId(id);
        storeUser2Redis(id, user);
        return BaseResponse.success(afterLogin);
    }

    /**
     * 存储用户信息到 redis
     * @param sessionId sessionId
     * @param user User
     */
    public void storeUser2Redis(String sessionId, User user){
        redisService.set(getKey(sessionId), user, TIME);
    }

    private String getKey(String sessionId){
        return "socket-upload:sid:" + sessionId;
    }

    public User getCacheUser(String sid) {
       return (User) redisService.get(getKey(sid));
    }
}
